from selenium import webdriver;
from selenium.webdriver import ChromeOptions;
# 动作链
from selenium.webdriver import ActionChains;
# 截图操作
from PIL import Image;
import base64,time,chaojiying;


options = ChromeOptions();
# 设置窗口启动位置 x,y
# options.add_argument('window-position=500,0');
# 无界面
# options.add_argument("headless");
# options.add_argument("disable-gpu");

bro = webdriver.Chrome(executable_path="../chromedriver.exe", options=options);
bro.get("https://kyfw.12306.cn/otn/resources/login.html");
page_text = bro.page_source;
time.sleep(1);

# 浏览器最大化
bro.maximize_window();

# 获取到 链接文本是"账号登录"得
a_tag = bro.find_element_by_link_text("账号登录");
a_tag.click();
time.sleep(1);

# 验证码图片保存操作1 下载图片 start ------------------------------------
img_tag = bro.find_element_by_id("J-loginImg");
src = img_tag.get_attribute("src");
src = src.split("data:image/jpg;base64,");

# 判断图片格式
suffix = "png";
if src[0].find("jpg") or src[0].find("jpeg"):
    suffix = "jpg";

# base64格式的图片 转换
imgdata = base64.b64decode(src[1]);
with open('./code.%s'%suffix,'wb') as wf:
    wf.write(imgdata);
# 验证码图片保存操作1 下载图片 end ------------------------------------

# 验证码图片保存操作2 截图 start ------------------------------------
# 将当前浏览器页面截图并保存
bro.save_screenshot("./html.png");
# 获取img验证码标签得位置
location = img_tag.location;
size = img_tag.size;

# 截图位置设置 左上,左下,右上,右下
rangle = (int(location['x']),int(location['y']),(int(location['x']) + int(size['width'])),(int(location['y']) + int(size['height'])));

# 实例化截图操作
cover = Image.open("html.png");
frame = cover.crop(rangle);
frame.save("./code.png");
# 验证码图片保存操作2 截图 end ------------------------------------

# 用户名,密码输入
u_input = bro.find_element_by_id('J-userName');
p_input = bro.find_element_by_id('J-password');
u_input.send_keys("15145450124");
time.sleep(0.5);
p_input.send_keys("YPFL31125");

# 超级鹰 验证码解析
Chaojiying_Client = chaojiying.Chaojiying_Client('yanpengfei', 'YPFL-31125', '913189');  # 用户中心>>软件ID 生成一个替换 96001
im = open('./code.png', 'rb').read();  # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
cjy = Chaojiying_Client.PostPic(im, 9004);
print("超级鹰返回: ",cjy);
location_str = cjy['pic_str'];
location_arr = location_str.split('|');
print("超级鹰返回坐标位置: ",location_arr);

# 模拟验证码点击
for item in location_arr:
    if "," in item:
        x = int(item.split(",")[0]);
        y = int(item.split(",")[1]);
        ActionChains(bro).move_to_element_with_offset(img_tag,x,y).click().perform();

time.sleep(0.5);

# 点击登录
login_btn = bro.find_element_by_id("J-login");
login_btn.click();
time.sleep(0.5);

# 模拟滑块拖动
slide = bro.find_element_by_id("nc_1_n1z");
slide_box = bro.find_element_by_id("nc_1_wrapper");
slide_box_size = slide_box.size;
x = int(slide_box_size['width']);

ActionChains(bro).click_and_hold(slide).move_by_offset(x,0).perform();



